package com.lx.blogflux.web;


import com.lx.blogflux.dao.ArticleDao;
import com.lx.blogflux.dao.UserDao;
import com.lx.blogflux.entity.Article;
import com.lx.blogflux.entity.User;
import com.lx.blogflux.util.Utils;
import com.lx.blogflux.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RestController
@Slf4j
public class IndexDo {

    @Autowired
    UserDao userDao;

    @Autowired
    ArticleDao articleDao;

    @RequestMapping("hello/{name}")
    Mono<Result> hello(@PathVariable String name){
        return Mono.just("hello" + name).map(Result::ok);
    }


    @RequestMapping("name")
    Flux<User> findById(String name){
        return userDao.findByName(name);
    }

    @RequestMapping("id")
    Mono<User> findById(int id){
        return userDao.findById(id);
    }

    @RequestMapping("query")
    public Mono<?> findByIntro(User user,
                               @RequestParam(defaultValue = "1") int page,
                               @RequestParam(defaultValue = "1") int size){
        // 构建查询条件
        ExampleMatcher matcher = ExampleMatcher.matching();
        if(!Utils.isEmpty(user.getIntro())){
            System.out.println("user = " + user);
            matcher = matcher.withMatcher("intro", ExampleMatcher.GenericPropertyMatchers.contains());
        }
        Example example = Example.of(user, matcher);

        // 构建查询条件
//        ExampleMatcher matcher = ExampleMatcher.matching();
//        if (!Utils.isEmpty(article.getTitle())) {
//            // 模糊查询
//            matcher = matcher.withMatcher("title", ExampleMatcher.GenericPropertyMatchers.contains());
//        }
//        Example example = Example.of(article, matcher);

        return userDao
                .findAll(example)
//                .findByIntroLike("%" + user.getIntro() + "%")
                .skip((page - 1) * size)
                .take(size)
                .collectList()
                .zipWith(userDao.count(example),
                        (a, b)-> Utils.asMap("records", a, "total", b));
    }

}
